import logging

from qiniu import Auth, put_data

# 绑定 Access_key Secret_key
access_key = 'cRn_IgG74ge-1BA2g05pno_WcaEUe3I8Fdn7TRK5'
secret_key = 'GBKRnHy4TECD86SIa0us4LBwEm-kPNWEXr74cmvv'

# 上传空间名
bucket_name = 'python7-dengdeyan'


def storage(data):
    """七牛云存储上传文件接口"""

    if not data:
        return

    try:
        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        # 生成上传 Token   可以指定过期时间
        token = q.upload_token(bucket_name)
        # 上传文件, 有返回值,第一个为key,第二个为上传状态
        ret, info = put_data(token, None, data)

    except Exception as e:
        logging.error(e)
        raise e

    if info and info.status_code != 200:
        raise Exception('上传文件失败')

    # 返回七牛云文件地址(前缀加上地址可以找到文件)
    return ret['key']

if __name__ == '__main__':
    file_name = input("请输入上传文件:")
    with open(file_name, 'rb') as f:
        print(storage(f.read()))